package Tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:Tcp
 * User: lenovo
 * Date: 2022-10-18
 * Time: 13:43
 */
public class TcpEchoServe {
    //服务器流套接字
    ServerSocket listenSocket = null;
    public TcpEchoServe(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true){
            //1.先调用accept来接受客户端的连接,返回的对象是一个Socket
            //有客户端连接后，返回一个服务端Socket对象，并基于该Socket建立与客户端的连接，否则阻塞等待
            Socket clienSocket = listenSocket.accept();
            //2.在有客户连接后处理连接
            //此处应该使用多线程,每个客户端连上来都得分配一个新的线程负责处理~~
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clienSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });


        }
    }

    private void processConnection(Socket clienSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n",clienSocket.getInetAddress().toString(),
        clienSocket.getPort());
        //接下来是处理客户端的请求了
        try(InputStream inputStream = clienSocket.getInputStream();
            OutputStream outputStream = clienSocket.getOutputStream()){
            while(true){
                //1.读取请求并解析
                //使用Scanner来包装inputStream
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    //读完了,连接可以断开了
                    System.out.printf("[%s:%d] 客户端下线\n",clienSocket.getInetAddress().toString(),
                            clienSocket.getPort());
                    break;
                }
                //读取客户端的请求
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应写回给客户端
                //使用PrintWriter包装outputStream
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓存区,确保数据确实是通过网卡发送出去了
                printWriter.flush();

                //打印日志
                System.out.printf("[%s:%d] req: %s; resp: %s\n",clienSocket.getInetAddress().toString(),
                        clienSocket.getPort(),request,response);
            }


        } catch (IOException e) {

            e.printStackTrace();
        }finally {
            //关闭clientSocket 为啥listenSocket和udp里的socket没有关闭
            clienSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServe serve = new TcpEchoServe(9090);
        serve.start();
    }
}
